package com.coocaa.x.app.framework.app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.util.Log;

import com.coocaa.x.app.framework.app.LiteAppApplication.ContentAppChangedReceiver.ContentAppChangedReceiverListener;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.FileUtils;
import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.BroadcastAction;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.logsdk.sky.LogSdkSqliteImpl;

import org.litepal.tablemanager.Connector;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class LiteAppApplication extends CoocaaApplication {

    @Override
    public void onCreate() {
//        try {
        super.onCreate();
        initLitePal();
        initContentAppChangedReceiver();
        initLogDatabase();
//        } catch (Exception e) {
//            e.printStackTrace();
//            uninstallSelf(this);
//        }
        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                LiteContentServiceConnecter.init();
                LogAPIForAppStore.appInit(getContext(), getMAC(), "", getAPPVersion(),
                        getDeviceChannel(), SystemProperties.get("ro.product.brand"),
                        SystemProperties.get("ro.build.skymodel")); // 还需要收集activity的日志，所以这个不能放在线程中，需要询问沈姝是否有优化空间

            }
        });
    }

    private void initLogDatabase() {
        String path = getFilesDir() + "/appstore_log/";
        if (!(new File(path).exists()))
            new File(path).mkdir();
        LogSdkSqliteImpl.setPath(path);
        LogSdkSqliteImpl.getInstance();
    }

    private void initContentAppChangedReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastAction.APPCHANGEDBROASTCAST);
        getContext().registerReceiver(ContentAppChangedReceiver.getInstance(), filter);
    }

    private void initLitePal() {
        try {
            Connector.getDatabase();
        } catch (Exception e) {
            e.printStackTrace();
            String file = "/data/data/" + getContext().getPackageName() + "/databases";
            FileUtils.deleteAll(new File(file));
            Connector.getDatabase();
        }
    }

    @Override
    protected synchronized String _getContentChannel() {
//        if (Android.isPackageInstalled(getContext(), "com.developer.fans"))
//            return "SkyFans";
        return super._getContentChannel();
    }

    public static String getDeviceChannel() {
        Context context = CoocaaApplication.getContext();
        String channel = (String) Android.getMetaData(context, context.getPackageName(),
                "UMENG_CHANNEL");
        if (channel == null || channel.equals("")) {
            LogUtils.e("getDeviceChannel failed,ues Common instead!!");
            channel = "Common";
        }
        return channel;
    }

    public static boolean isMarketChannel() {
        return getDeviceChannel().toLowerCase().startsWith("market");
    }

    public static boolean isSkyDongle() {
        return getDeviceChannel().toLowerCase().startsWith("skydongle");
    }

    public static boolean isCommonChannel() {
        return getDeviceChannel().toLowerCase().startsWith("common");
    }

    public static class ContentAppChangedReceiver extends BroadcastReceiver {
        private static ContentAppChangedReceiver instance = new ContentAppChangedReceiver();

        public synchronized static ContentAppChangedReceiver getInstance() {
            return instance;
        }

        public static interface ContentAppChangedReceiverListener {
            public void onAction(Intent i);
        }

        private List<ContentAppChangedReceiverListener> list = new ArrayList<ContentAppChangedReceiverListener>();

        public void addListener(ContentAppChangedReceiverListener i) {
            synchronized (list) {
                list.add(i);
            }
        }

        public void removeListener(ContentAppChangedReceiverListener i) {
            synchronized (list) {
                list.remove(i);
            }
        }

        @Override
        public void onReceive(Context c, Intent intent) {
            synchronized (list) {
                if (list.size() < 1) {
                    return;
                }
                LogUtils.d("intent", "android.intent.action.PACKAGE_ADDED");
                for (ContentAppChangedReceiverListener i : list) {
                    try {
                        i.onAction(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void addContentAppChangedReceiverListener(ContentAppChangedReceiverListener l) {
        ContentAppChangedReceiver.getInstance().addListener(l);
    }

    public static void removeContentAppChangedReceiverListener(ContentAppChangedReceiverListener l) {
        ContentAppChangedReceiver.getInstance().removeListener(l);
    }

    public static String getServer(String path) {
        return (String) Android.getMetaData(getContext(), getContext().getPackageName(), "SERVER")
                + "/" + path;
    }

    public synchronized static boolean isFirstStart() {
        boolean isNewApp = isNewApp();
        boolean canShowGuide = canShowGuide();    //不要图代码简单，就要这么繁琐写，不然会出导航画面重复的问题的
        LogUtils.d("start", "isFirstStart isNewApp:" + isNewApp + " canShowGuide:" + canShowGuide);
        return (isNewApp || canShowGuide);
    }

    private static Boolean bCanShowGuide = null;

    public static void destroy() {
        bCanShowGuide = null;
    }

    public static boolean canShowGuide() {
        if (bCanShowGuide == null) {
            try {
                bCanShowGuide = XServiceManager.getLiteConfigService().getBooleanValue(
                        "show_guide", true);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
//            try {
//                XServiceManager.getLiteConfigService().saveBooleanConfig("show_guide", false);
//            } catch (RemoteException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
        }
        return bCanShowGuide;
    }

    public static void saveShowGuide() {
        try {
            XServiceManager.getLiteConfigService().saveBooleanConfig("show_guide", false);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static String getCurUser() {
        String name = "";
        try {
            name = XServiceManager.getLiteCCConnectorService().getCurUserPoints();
        } catch (Exception e) {

        }
        return name;
    }

    public static boolean getFirstLaunch(String clsName) {
        String curUser = getCurUser();
        String values = "";
        try {
            values = XServiceManager.getLiteConfigService().getStringValue(
                    clsName, "");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        LogUtils.d("PointResult", "sunny point getFirstLaunch 2:" + values + "; " + curUser);
        if (curUser != null && !curUser.equals("") && values != null && !values.equals("") && curUser.equals(values)) {
            return true;
        }
        return false;
    }

    public static void setFirstLaunch(String clsName) {
        String curUser = getCurUser();
        LogUtils.d("PointResult", "sunny point setFirstLaunch:" + clsName + "; " + curUser);
        if (curUser != null && !curUser.equals("")) {
            try {
                XServiceManager.getLiteConfigService().saveStringConfig(
                        clsName, curUser);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean isNewApp() {
        String versionCode = getAppVersionCode();
        String ver = "";
        try {
            ver = XServiceManager.getLiteConfigService().getStringValue("versionname", "0");
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        LogUtils.d("vc", "versionshar:" + versionCode + " ver:" + ver);
        if (!versionCode.equals(ver)) {
            try {
                XServiceManager.getLiteConfigService().saveStringConfig("versionname", versionCode);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }


    /**
     * 判断网络连接状态，在未连接时弹出连接网络提示框
     *
     * @param showToast 弹出toast的具体实现runnable，可不传，在coocaa5.0以下的版本或系统弹出对话框失败的情况下才会使用
     * @return true:已连接  false:未连接
     */
    public static boolean checkNetworkConnection(Runnable showToast) {
        if (Android.isNetConnected(CoocaaApplication.getContext()))
            return true;
        try {
            if (CoocaaApplication.isCoocaaSystem() && CoocaaApplication.getCoocaaVersion().major >= 5) {
                if (!XServiceManager.getLiteCCConnectorService().showConnectNetworkDialogWithConfirmUI()) {
                    if (showToast != null)
                        LiteHandlerThread.postOnUiThread(showToast);
                }
            } else {
                if (showToast != null)
                    LiteHandlerThread.postOnUiThread(showToast);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (showToast != null)
                LiteHandlerThread.postOnUiThread(showToast);
        }
        return false;
    }
}
